﻿using Common.Communal;
using ERP.Domain.CustomerSupplier;
using ERP.Domain.Scheduling;
using MediatR;
using Sell.Api.Read.Application.Command.CustomerCommand;
using SqlSugar;

namespace Sell.Api.Read.Application.CommandHandlers.CustomerCommandHandler
{
    public class CustomerlistCommandHandlers : IRequestHandler<CustomerlistCommand, ApiResult<ApiPaging<Customer>>>
    {
        public ISqlSugarClient SqlSugar { get; }
        public CustomerlistCommandHandlers(ISqlSugarClient sqlSugar)
        {
            SqlSugar = sqlSugar;
        }
        /// <summary>
        /// 客户管理列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<ApiPaging<Customer>>> Handle(CustomerlistCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<Customer>> result = new ApiResult<ApiPaging<Customer>>();
            result.Code = EnumCode.Ok;
            result.Message = "客户显示成功";

            // 只查询IsDelete为false的记录
            var query = SqlSugar.Queryable<Customer>().Where(x => x.IsDelete == false);
            if (!string.IsNullOrEmpty(request.CustomerName))
            {
                query = query.Where(x => x.CustomerName.Contains(request.CustomerName));
            }
            if (!string.IsNullOrEmpty(request.CustomerType))
            {
                query = query.Where(x => x.CustomerType.Equals(request.CustomerType));
            }
            if (request.State != null)
            {
                query = query.Where(x => x.State.Equals(request.State));
            }
            var list = query.ToList();
            int totalcount = list.Count();
            int totalpage = (int)Math.Ceiling(totalcount * 1.0 / request.pagesize);
            list = list.OrderBy(x => x.Id).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize).ToList();
            ApiPaging<Customer> paging = new ApiPaging<Customer>();
            paging.TotalCount = totalcount;
            paging.TotalPage = totalpage;
            paging.Data = list.ToList();
            result.Data = paging;
            return Task.FromResult(result);
        }
    }
}
